package com.test.rest.server;

import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/customerservice/")
public class CustomerService {

	long currentId = 123;
	
	private Map<Long, Customer> customers = new HashMap<Long, Customer>();
	
	private Map<Long, Order> orders = new HashMap<Long, Order>();
	
	public CustomerService() {
		
		Customer customer = new Customer();
		
		customer.setId(123);
		customer.setName("zhangsan");
		
		customers.put(customer.getId(), customer);
		
		Order order = new Order();
		
		order.setId(223);
		order.setDescription("order 223");
		
		orders.put(order.getId(), order);
	}
	
	
	@GET
	@Path("/customers/{id}/")
	public Customer getCustomer(@PathParam("id") String id) {
		
		long idNumber = Long.parseLong(id);
		
		Customer customer = customers.get(idNumber);
		
		return customer;
		
	}
	
	
	@Path("/orders/{orderId}")
	public Order getOrder(@PathParam("orderId") String orderId) {
		
		long idNumber = Long.parseLong(orderId);
		
		return this.orders.get(idNumber);
		
	}
	
	@PUT
	@Path("/customers/")
	public Response updateCustomer(Customer customer) {
		
		Customer c = this.customers.get(customer.getId());
		
		Response r = null;
		
		if (null != c) {
			
			this.customers.put(customer.getId(), customer);
			
			r = Response.ok().build();
			
		} else {
			
			r = Response.notModified().build();
			
		}
		
		return r;
		
	}
	
	@POST
	@Path("/customers/")
	public Response addCustomer(Customer customer) {
		
		customer.setId(++this.currentId);
		
		this.customers.put(customer.getId(), customer);
		
		return Response.ok(customer).build();
		
	}
	
	@DELETE
	@Path("/customers/{id}")
	public Response deleteCustomer(@PathParam("id") String id) {
		
		long idNumber = Long.parseLong(id);
		
		Customer c = this.customers.get(idNumber);
		
		Response r = null;
		
		if (null != c) {
			
			this.customers.remove(idNumber);
			r = Response.ok().build();
			
		} else {
			r = Response.notModified().build();
		}
		
		return r;
	}
	
}
